/**
 * 上海中赢金融信息服务有限公司
 * Copyright (c) 2016-2026 HMC,Inc.All Rights Reserved.
 */
package com.sys.midware.httpClient.utils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sys.midware.httpClient.crawler.Crawler;
import com.sys.midware.httpClient.crawler.HttpException;

/**
 * 
 * <b>Description：</b> http工具类 <br/>
 * <b>ClassName：</b> HttpUtils <br/>
 * <b>@author：</b> jackyshang <br/>
 * <b>@date：</b> 2016年7月1日 上午10:21:51 <br/>
 * <b>@version: </b> <br/>
 */
public class HttpUtils {

    private static final Logger logger = LoggerFactory.getLogger(HttpUtils.class);

    private static final int DEFAULT_TIMEOUT = 15000;

    /**
     * 
     * @param url
     * @return
     * 
     * @throws HttpException
     */
    public static String get(String url) {
        return get(url, DEFAULT_TIMEOUT);
    }

    /**
     * return empty string if exception
     * 
     * @param url
     * @param timeOutMills
     * @return
     * 
     * @throws HttpException
     */
    public static String get(String url, int timeOutMills) {
        try {
            return Crawler.get().timeOut(timeOutMills).crawl(url).retry(3).resultAsString();
        } catch (HttpException e) {
            logger.error("url {} timeout {} {}", url, timeOutMills, e.getMessage(), e);
            throw e;
        } catch (Exception e) {
            logger.error("url {} got error", url, e);
        }
        return StringUtils.EMPTY;
    }

    /**
     * return null if exception
     * 
     * @param url
     * @param timeOutMills
     * @return
     * 
     * @throws HttpException
     */
    public static byte[] getByte(String url, int timeOutMills) {
        try {
            return Crawler.get().timeOut(timeOutMills).crawl(url).retry(3).resultAsByte();
        } catch (HttpException e) {
            logger.error("url {} timeout {} {}", url, timeOutMills, e.getMessage(), e);
            throw e;
        } catch (Exception ignore) {

        }
        return null;
    }

    public static String getPost(String strURL, String params) {
        try {
            URL url = new URL(strURL);// 创建连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestMethod("POST"); // 设置请求方式
            connection.setRequestProperty("Accept", "application/json"); //
            // 设置接收数据的格式
            connection.connect();
            OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); // utf-8编码
            out.append(params);
            out.flush();
            out.close();
            // 读取响应
            int length = (int) connection.getContentLength();// 获取长度
            InputStream is = connection.getInputStream();
            if (length != -1) {
                byte[] data = new byte[length];
                byte[] temp = new byte[512];
                int readLen = 0;
                int destPos = 0;
                while ((readLen = is.read(temp)) > 0) {
                    System.arraycopy(temp, 0, data, destPos, readLen);
                    destPos += readLen;
                }
                return new String(data, "UTF-8");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "error";
    }

    /**
     * return null if exception
     * 
     * @param url
     * @param timeOutMills
     * @return
     * 
     * @throws HttpException
     */
    public static byte[] getByte(String url) {
        return getByte(url, DEFAULT_TIMEOUT);
    }

}
